using Godot;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text.Json;
using TopDownGodot.Src.Globals.Multiplayer;

namespace TopDownGodot.Src.Multiplayer
{
    public partial class SendPactedUdp : Node
    {
        private readonly UdpClient _sendudpClient = new();
        private readonly int _deskPort = 4433;

        // 每隔5秒广播一次房间（发送数据包） 
        public void OnPacketSendTimerTimeout()
        { 
            if (!(MultiplayerGlobal.IsMultiplayer && Multiplayer.IsServer()))
                return;
            GD.Print("--------------------------------------------------------");
            foreach (var item in MultiplayerGlobal.RoomInfo)
            {
                string roomInfoJson = JsonSerializer.Serialize(item);
                byte[] data = System.Text.Encoding.UTF8.GetBytes(roomInfoJson);
                try
                {
                    var error = _sendudpClient.Send(data, data.Length, GetBroadcastAddress(item.Ip, item.Mask), _deskPort);
                    GD.Print($"\nPacket sent success!\ndata = {roomInfoJson}\nDesk port:{_deskPort}\n");
                }
                catch (SocketException ex)
                {
                    Console.WriteLine($"发送数据包失败: {ex.ErrorCode} - {ex.Message}");
                }
            }
        }

        private string GetBroadcastAddress(string ipAddress, string subnetMask)
        {
            // 将IP地址和子网掩码转换为字节数组
            byte[] ipBytes = IPAddress.Parse(ipAddress).GetAddressBytes();
            byte[] maskBytes = IPAddress.Parse(subnetMask).GetAddressBytes();

            if (ipBytes.Length != maskBytes.Length)
                throw new ArgumentException("IP地址和子网掩码长度不匹配");

            byte[] broadcastBytes = new byte[ipBytes.Length];

            // 计算广播地址：IP OR (NOT 掩码)
            for (int i = 0; i < broadcastBytes.Length; i++)
            {
                broadcastBytes[i] = (byte)(ipBytes[i] | (byte)~maskBytes[i]);
            }

            return new IPAddress(broadcastBytes).ToString();
        }
    }
}
